<template>
    <div style=" position: relative;">
        <el-card>
            <template #header>
                <!-- 搜索 -->
                <div style="display:flex;    align-items: center;">
                    <el-input style="width: 360px;" v-model="findCusWalletPages_find_data.find"
                        placeholder="请输入客户名称电话、单位名称" clearable prefix-icon="User" />

                    <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                        icon="Search">搜索</el-button>
                    <div ref="dgtools" class="filter-container">
                        <div class="dgts-row">
                            <div class="dgts-text-tj1">
                                <b style='font-weight:700;' class="tr-it-title">统计</b>
                                <el-divider direction="vertical"></el-divider>
                                <b style='font-weight:700;color:red'>现金余额:{{ tj.totalPrice || 0
                                    }}元</b>
                                <el-divider direction="vertical"></el-divider>
                                <b style='font-weight:700;color:green'>冻结巴士币:{{ tj.agentPrice || 0 }}元</b>
                                <el-divider direction="vertical"></el-divider>
                                <b style='font-weight:700;color:red'>可用巴士币:{{ tj.alreadyAgentPrice || 0 }}元</b>
                                
                            </div>


                        </div>
                    </div>
                </div>
                <!-- 功能按钮 -->
                <div style="margin-top:10px;">
                    <el-button @click="re_wallet_btn" type="primary" icon="SuccessFilled">充值</el-button>
                    <el-button @click="se_wallet_btn" type="warning" icon="Tools">信用额度设置</el-button>
                    <el-button @click="ex_wallet_btn" type="warning" icon="Share">导出</el-button>
                </div>
            </template>
            <div>
                <el-table border @selection-change="selection_change_btn" height="67vh" ref="multipleTableRef"
                    :data="findCusWalletPages_list_data" style="width: 100%">
                    <el-table-column type="selection" width="35" />
                    <el-table-column label="编号" width="55" fixed type="index" />

                    <template v-for="item in table_data_list_new" :key="item.field">
                        <el-table-column v-if="item.off" :width="item.width" :prop="item.field" :label="item.label">
                        </el-table-column>
                    </template>
                </el-table>
            </div>

            <div style="margin-top:20px">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="findCusWalletPages_find_data.page.pageNum"
                    v-model:page-size="findCusWalletPages_find_data.page.pageSize" :page-sizes="[20, 50, 100, 200]"
                    :background="true" layout="prev, pager, next, jumper,->,sizes,total," :total="total" />
            </div>
        </el-card>
        <!-- 弹窗 -->
        <div>
            <!-- 表格筛选 -->
            <div style="position: absolute;top:75px;z-index: 2;" :style="icon_off ? 'right:0px;' : 'right:110px;'">
                <el-icon @click="icon_btn" :size="20">
                    <Setting />
                </el-icon>
                <div v-show="icon_off"
                    style=" position: relative;top:-100px;right:140px;width: 130px;height:430px;background:#fff;overflow: hidden;">
                    <div class="cols-set" style="background:#fff;width:90%;height:97%;margin:auto;margin-top:10px;">
                        <div>
                            <el-button-group style="display: flex; ">
                                <el-tooltip effect="dark" placement="bottom">
                                    <template #content>注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！ </template>
                                    <el-button style="width:10px" type="primary" icon="WarningFilled"></el-button>
                                </el-tooltip>
                                <el-button title="重置" type="primary" icon="Refresh" @click="resetTableSet"></el-button>
                                <el-button title="保存" type="primary" icon="Check" @click="saveTableSet"></el-button>
                            </el-button-group>
                            <div ref="sortableContainer" class="col-items" style="height:400px; overflow-y: auto; ">
                                <el-checkbox class="drag_it" @change="checkbox_btn" v-for="item in sortedItems"
                                    :key="item.field" v-model="item.off" :label="item.label" border>
                                </el-checkbox>
                            </div>

                        </div>
                    </div>
                </div>
            </div>
            <!-- 充值 -->
            <!-- 客户价格配置 -->
            <el-dialog v-model="userRecharge_off" title="用户余额充值：" width="30%" :close-on-click-modal="false">
                <div>
                    <el-form :model="userRecharge_data" label-width="85px">
                        <el-form-item label="充值金额：">
                            <el-input type="number" v-model.number="userRecharge_data.count" placeholder="请输入充值金额：" />
                        </el-form-item>
                        <el-form-item label="充值类型：">
                            <el-select v-model="userRecharge_data.rechargeType" :placeholder="'充值类型'">
                                <el-option :label="'余额'" :value="'0'"></el-option>
                                <el-option :label="'巴士币'" :value="'1'"></el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="充值备注：">
                            <el-input placeholder="请输入充值备注：" v-model="userRecharge_data.note" type="textarea"
                                show-word-limit maxlength="30" />
                        </el-form-item>
                    </el-form>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="userRecharge_off = false">取消</el-button>
                        <el-button type="primary" @click="userRecharge_ok_btn">
                            确认
                        </el-button>
                    </span>
                </template>
            </el-dialog>

            <!-- 信用额度 -->
            <el-dialog v-model="backSet_off" title="用户信用额度设置：" width="30%" :close-on-click-modal="false">
                <div>
                    <el-form :model="backSet_data" label-width="85px">
                        <el-form-item label="额度金额：">
                            <el-input placeholder="请输入额度金额：" type="number" v-model.number="backSet_data.count"
                                onkeyup="value=value.replace(/^(0+)|[^\d]+/g,'')" />

                        </el-form-item>
                        <el-form-item label="额度备注：">
                            <el-input placeholder="请输入额度备注：" v-model="backSet_data.note" type="textarea" show-word-limit
                                maxlength="30" />
                        </el-form-item>
                        <span style="color:red;font-weight:700;">*注：用户信用额度金额只能为正整数</span>
                    </el-form>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="backSet_off = false">取消</el-button>
                        <el-button type="primary" @click="backSet_ok_btn">
                            确认
                        </el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import Sortable from 'sortablejs';
import { ref, reactive, onMounted, computed } from 'vue'
import CircularJSON from 'circular-json'
import { findCusWalletPages, expCusWallet, userRecharge, backSetCreditBalance, adupPrivateSet, getPrivateSetList } from '@/api/customer_list.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import * as XLSX from 'xlsx';
onMounted(async () => {
    let wallet_list = JSON.parse(localStorage.getItem('wallet_list'))
    if (wallet_list) {
        findCusWalletPages_find_data.find = wallet_list.find
    }

    getPrivateSetList({
        find: '钱包列表',
        page: {
            pageNum: 1,
            pageSize: 20,
        },
    }).then(res => {
        if (res.data.list[0]) {
            table_data_list_new.value = JSON.parse(res.data.list[res.data.list.length - 1].dat)
        } else {
            table_data_list_new.value = table_data_list
        }
    })


    Sortable.create(sortableContainer.value, {
        draggable: '.drag_it',
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
            const targetRow = table_data_list_new.value.splice(evt.oldIndex, 1)[0];
            table_data_list_new.value.splice(evt.newIndex, 0, targetRow);

            // 重新赋值给列数组
            // let cols = that.U.scopy(that.fields);
            // let list = cols.filter(it => { return it.show; });
            // that.$emit('saveSet', {dgName: that.dgName, cols: list});
        }
    })

    await findCusWalletPages_list()
})
const tj = reactive({
    // 订单总价
    totalPrice: 0,
    // 可提成总金额
    agentPrice: 0,
    // 已提成总金额
    alreadyAgentPrice: 0,


})
//#region 表格数据处理
const table_data_list = reactive([
    { label: '客户名称', field: 'realName', width: '', off: true },
    { label: '客户电话', field: 'loginPhone', width: '', off: true },
    { label: '单位名称', field: 'companyName', width: '', off: true },
    { label: '现金余额', field: 'cashBalance', width: '', off: true },
    { label: '信用额度', field: 'creditBalance', width: '', off: true },
    { label: '可用巴士币', field: 'recomPointBalance', width: '', off: true },
    { label: '冻结巴士币', field: 'freezePointBalance', width: '', off: true },
    { label: '添加时间', field: 'addTime', width: '', off: true },
])

const table_data_list_new = ref([])
const icon_off = ref(false)
// 创建排序容器的引用
const sortableContainer = ref('')

const icon_btn = () => {
    icon_off.value = !icon_off.value
    console.log(sortableContainer.value)

}
const resetTableSet = () => {
    console.log(table_data_list)
    table_data_list_new.value = JSON.parse(JSON.stringify(table_data_list))
    console.log(table_data_list)
    console.log(table_data_list_new.value)
}
const saveTableSet = () => {
    adupPrivateSet({
        dat: JSON.stringify(table_data_list_new.value),
        tbName: '钱包列表',
        tbNum: "wallet_list",
    }).then(res => {
        if (res.code == 1) {
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
    icon_off.value = false
}

const checkbox_btn = (e, c) => {
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (table_data_list_new.value[i].label == c.target._value) {
            table_data_list_new.value[i].off == e

        }

    }

}

const sortedItems = computed(() => {
    return [...table_data_list_new.value].sort((a, b) => a.id - b.id);
})
//#endregion




//#region 钱包分页列表
const findCusWalletPages_list_data = ref([])
const findCusWalletPages_find_data = reactive({
    page: {
        pageNum: 1,
        pageSize: 20,
    },
    find: ''
})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    findCusWalletPages_find_data.page.pageNum = 1
    findCusWalletPages_list()
}

// 分页器跳转页面
const current_change_btn = () => {
    findCusWalletPages_list()
}

const findCusWalletPages_list = () => {

    findCusWalletPages(findCusWalletPages_find_data).then(res => {
        findCusWalletPages_list_data.value = res.data.list.list
        total.value = res.data.list.total
        tj.totalPrice = res.data.statics.sumCashBalance
        tj.agentPrice = res.data.statics.sumFreezePointBalance
        tj.alreadyAgentPrice = res.data.statics.sumRecomPointBalance
    })
}
//#endregion

//#region 搜索
const search_btn = () => {
    localStorage.setItem('wallet_list', CircularJSON.stringify(findCusWalletPages_find_data))
    findCusWalletPages_list()
}
//#endregion

//#region 表格选择
const table_list = ref([])
const selection_change_btn = (e) => {
    table_list.value = e
    console.log('表格选择的数据', e)
}
//#endregion

//#region 充值
const userRecharge_off = ref(false)
const userRecharge_data = reactive({
    count: '',
    cwReqParam: "cwReqParam",
    note: "",
    userId: "",
    rechargeType: '0',
})
const re_wallet_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }
    userRecharge_data.count = ''
    userRecharge_data.userId = table_list.value[0].userId
    userRecharge_data.note = ''
    userRecharge_data.rechargeType = '0'
    userRecharge_off.value = true
}

const userRecharge_ok_btn = () => {
    if (!userRecharge_data.count) {
        return ElMessage({
            message: '请输入充值金额！',
            type: 'warning',
        })
    }
    let loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    userRecharge(userRecharge_data).then(res => {
        if (res.code == 1) {
            findCusWalletPages_list()
            loading.close()
            userRecharge_off.value = false
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            loading.close()
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }

    })
}
//#endregion

//#region 信用额度设置
const backSet_off = ref(false)
const backSet_data = reactive({
    count: '',
    cwReqParam: "cwReqParam",
    note: "",
    userId: '',
})
const se_wallet_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }
    backSet_data.count = ''
    backSet_data.userId = table_list.value[0].userId
    backSet_data.note = ''
    backSet_off.value = true
}

const backSet_ok_btn = () => {
    if (!backSet_data.count) {
        return ElMessage({
            message: '请输入设置金额！',
            type: 'warning',
        })
    }
    let loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    backSetCreditBalance(backSet_data).then(res => {
        if (res.code == 1) {
            findCusWalletPages_list()
            loading.close()
            backSet_off.value = false
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            loading.close()
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }

    })
}
//#endregion

//#region 钱包导出
const ex_wallet_btn = () => {
    let ps = {
        find: findCusWalletPages_find_data.find,
    }
    expCusWallet(ps).then(res => {
        if (res.code == 1) {
            const data = [
                ['客户电话', '单位名称', '现金余额', '信用额度', '推广积分'],
            ];
            for (let i = 0; i < res.data.length; i++) {
                let ps = {
                    realName: res.data[i].realName,
                    loginPhone: res.data[i].loginPhone,
                    companyName: res.data[i].companyName,
                    cashBalance: res.data[i].cashBalance,
                    creditBalance: res.data[i].creditBalance,
                    recomPointBalance: res.data[i].recomPointBalance,


                }
                data.push(Object.values(ps))
            }
            const ws = XLSX.utils.aoa_to_sheet(data);
            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
            XLSX.writeFile(wb, '客车帮服务后台系统管理-钱包列表.xlsx');
            findCusWalletPages_list()
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }

    })
}
//#endregion

</script>

<style scoped lang='scss'>
.filter-container {
    line-height: 30px;
    position: relative;

    .dgts-row {
        display: flex;
        line-height: 20px;
        margin-top: 5px;
        margin-bottom: 5px;
        margin-right: 30px !important;


        .dgts-text {
            line-height: 30px;
        }

        .tr-it-title {
            font-size: 15px;
        }

        .tr-it {
            font-size: 13px;
        }

        .dgts-text-tj1 {
            line-height: 30px;
            margin: 0px 10px;
            background: #fde2e2;
            border-radius: 5px;
            padding: 0px 10px;
        }

        .dgts-text-tj2 {
            line-height: 30px;
            margin: 0px 10px;
            background: #b3d8ff;
            border-radius: 5px;
            padding: 0px 10px;
        }

        /* 列表顶部工具栏统计等文本--end */

    }
}
</style>
<style>
.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}


.el-table .el-table__cell {
    padding: 0px !important;
}
</style>
